/**
 *@description 权限列表操作页面js
 *@author XieXing
 *@date 2020/8/23 15:33
 */
var table, form, layer, laydate, layedit, tree;//当前页面全局定义 TODO 继续优化
var module = {
    /**
     *@description 权限操作接口url集合 统一管理
     *@author XieXing
     *@date 2020/8/23 15:35
     */
    URL: {
        getDataListUrl: '/permission/getMenuList',//获取权限信息
        getTreeMenus: '/menu/getTreeMenus',//获取菜单树
        saveUrl: "/permission/save",//保存权限信息
        updateUrl: '/permission/update',//修改权限信息
        updateStatusUrl: function (id, status) {//更新权限状态
            return '/permission/' + id + '/' + status;
        },
        deleteUrl: function (id) {//删除权限
            return '/permission/' + id;
        }
    },
    /**
     *@description 初始化
     *@author XieXing
     *@date 2020/8/23 15:36
     */
    init: function () {
        layui.use(['form', 'table', 'layer', 'laydate', 'layedit', 'tree'], function () {
            tree = layui.tree;
            table = layui.table;
            form = layui.form;
            layer = layui.layer;
            laydate = layui.laydate;
            layedit = layui.layedit;
            var pageData = page.pageData();
            table.render({
                elem: '#datagrid',
                id: 'datagrid',
                url: module.URL.getDataListUrl,/*换成你的接口*/
                method: "GET",
                cols: [[
                    {type: 'radio', fixed: 'left'},
                    {type: 'numbers', title: '序号', fixed: "left"},
                    {field: 'permissionName', title: '权限名称', width: '10%'},
                    {
                        field: 'permissionCode',
                        title: '权限编码',
                        align: 'center',
                        width: '20%'
                    },
                    {
                        field: 'permissionUrl',
                        title: '权限url',
                        align: 'center',
                        width: '20%'
                    },
                    {field: 'permissionOfMenuId', title: '所属菜单', align: 'center', width: '10%'},
                    {field: 'permissionAddedby', title: '添加人', align: 'center', width: '10%'},
                    {field: 'permissionAddTime', title: '添加时间', align: 'center', width: '15%'},
                    {
                        field: 'permissionIsEnable', title: '状态', align: 'center', width: '12%',
                        fixed: 'right',
                        templet: function (d) {
                            var checked = "";
                            if (d.permissionIsEnable == 1) {
                                checked = "checked=true";
                            }
                            return "<input type='checkbox' " + checked + " id=" + d.id + " userName = " + d.userName + " name='userIsEnabled' lay-skin='switch' lay-text='启用|禁用' lay-event='test' lay-filter='switch'>"
                        }
                    }
                ]],
                height: pageData.tableHeight,
                limit: pageData.limit,
                limits: pageData.limits,
                page: true,
                response: {
                    statusCode: 200
                },
                parseData: function (res) { //res 即为原始返回的数据
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.stateInfo, //解析提示文本
                        "count": res.data.total, //解析数据长度
                        "data": res.data.list //解析数据列表
                    };
                },
                done: function (res, curr, count) {
                    var perPageMax = $(".layui-laypage-limits select option:last-child").val();//每页最大条数
                    page.tableLoadAll(count, perPageMax);//加载全部
                }
            });

            //监听单元格事件
            table.on('tool(datagrid)', function (obj) {
                if (obj.event === 'edit') {
                    module.edit_model_permission();
                }
            });

            /**
             *@description 监听表格中的switch
             *@author XieXing
             *@date 2020/8/18 22:48
             */
            form.on('switch(switch)', function (data) {
                var id = $(this).attr("id");
                var status = data.elem.checked ? 1 : 0;
                var loading = layer.load(1);
                $.post(module.URL.updateStatusUrl(id, status), {}, function (result) {
                    if (result && result.code === 200) {
                        layer.closeAll();
                        $("#btnSearch").trigger("click");
                    } else {
                        layer.close(loading);
                        layer.msg(result.err, {icon: 2, time: 2000});
                        return false;
                    }
                });
            });

            /**
             *@description 点击查询
             *@author XieXing
             *@date 2020/7/30 11:34
             */
            $("#btnSearch").on("click", function () {
                var qm = {};
                $("#queryForm").serializeArray().forEach(function (each) {
                    qm[each.name] = each.value;
                });
                var cur = parseInt($(".layui-laypage-skip input").val()) || 1;//当前页
                var limit = parseInt($(".layui-laypage-limits select").val()) || 10;//当前每页条数
                table.reload('datagrid', {
                    where: qm,
                    page: {curr: cur, limit: limit}
                });
                return false;
            });


            /**
             *@description 点击新增
             *@author XieXing
             *@date 2020/8/16 16:55
             */
            $("#btnAdd").click(function () {
                module.edit_model("新增权限", module.URL.saveUrl);
            });

            /**
             *@description 修改权限信息
             *@author XieXing
             *@date 2020/8/17 14:59
             */
            $("#btnUpdate").click(function () {
                var rowData = table.checkStatus('datagrid').data;
                if (rowData.length === 0) {
                    layer.msg("请至少选择一条数据。", {icon: 5, time: 2000});
                    return false;
                }
                rowData = rowData[0];
                module.edit_model("修改权限", module.URL.updateUrl, rowData);
            });

            /**
             *@description 删除权限
             *@author XieXing
             *@date 2020/8/17 22:32
             */
            $("#btnDelete").click(function () {
                var rowData = table.checkStatus('datagrid').data;
                if (rowData.length === 0) {
                    layer.msg("请至少选择一条数据。", {icon: 5, time: 2000});
                    return false;
                }
                rowData = rowData[0];
                layer.confirm("确认删除权限" + rowData.permissionName + "吗？", function () {
                    var loading = layer.load(1);
                    $.post(module.URL.deleteUrl(rowData.id), {}, function (result) {
                        if (result && result.code === 200) {
                            layer.closeAll();
                            $("#dataModel form")[0].reset();
                            $("#btnSearch").trigger("click");
                        } else {
                            layer.close(loading);
                            layer.msg(result.err, {icon: 2, time: 2000});
                            return false;
                        }
                    });
                });

            });

            $.post(module.URL.getTreeMenus, {}, function (result) {
                tree.render({
                    elem: '#ofMenu'
                    , data: result
                    , showCheckbox: false  //是否显示复选框
                    , id: 'demoId1'
                    , isJump: false //是否允许点击节点时弹出新窗口跳转
                    , click: function (obj) {
                        var data = obj.data;
                        $("#permissionOfMenuId").val(data.id);
                        $("#permissionOfMenuName").val(data.title);
                    }
                });
            });

        });
    },
    /**
     *@description 编辑弹出层
     *@author XieXing
     *@date 2020/8/18 22:00
     */
    edit_model: function (modelName, url, rowData) {
        layer.open({
            type: 1,
            area: ['80%', '60%'],
            title: modelName,
            content: $("#dataModel"),
            offset: ['20px'],
            btn: ['提交', '取消'],
            btn1: function (index, layero) {
                $("#formSubmitBtn").trigger("click");
                return false;
            },
            btn2: function (index, layero) {
                $("#dataModel form")[0].reset();
                layer.closeAll();
                return false;
            },
            cancel: function (layero, index) {
                $("#dataModel form")[0].reset();
                layer.closeAll();
            },
            success: function (layero, index) {
                if (rowData) {
                    module.getData(rowData);//非新增操作回填数据
                }
                form.on('submit(form_submit_btn)', function (data) {
                    var data = data.field;
                    if (rowData) { //rowData 存在表示修改权限信息
                        data.id = rowData.id;
                    }
                    var loading = layer.load(1);
                    $.post(url, data, function (result) {
                        if (result && result.code === 200) {
                            layer.closeAll();
                            $("#dataModel form")[0].reset();
                            $("#btnSearch").trigger("click");
                        } else {
                            layer.close(loading);
                            layer.msg(result.err, {icon: 2, time: 2000});
                            return false;
                        }
                    });
                    return false;
                });
            }
        });
    },
    /**
     *@description 对象回填数据
     *@author XieXing
     *@date 2020/8/17 15:02
     */
    getData: function (data) {
        for (var k in data) {
            $("input[name=" + k + "],select[name=" + k + "],textarea[name=" + k + "]").val(data[k]);
        }
        form.render();
    }

};
module.init();//运行初始化函数
